package dao.mysql;

import com.google.gson.JsonObject;
import entity.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AccountMySQLDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int add(Account a) {
        String sql = "INSERT INTO account (d_username, d_password, d_email) VALUE (?, ?, ?)";
        Object[] params = new Object[] { a.getD_username(), a.getD_password(), a.getD_email() };
        return this.jdbcTemplate.update(sql, params);
    }

    public Account verify(String account, String password) throws Exception {
        String sql = "SELECT * FROM account WHERE (d_username = ? OR d_email = ?) AND d_password = ?";
        BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
        Object[] params = new Object[] { account, account, password };
        List<Account> list = this.jdbcTemplate.query(sql, rowMapper, params);
        if(list.size() != 1) throw new Exception("Account does not exist or password incorrect!");
        return list.get(0);
    }

    public String query(String account) {
        String sql = "SELECT * FROM account WHERE d_username = ? OR d_email = ?";
        BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
        Object[] params = new Object[] { account, account };
        List<Account> list = this.jdbcTemplate.query(sql, rowMapper, params);
        return list.size() == 1 ? list.get(0).getD_username() : null;
    }

    public Account queryAsEntity(String account) {
        String sql = "SELECT * FROM account WHERE d_username = ? OR d_email = ?";
        BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
        Object[] params = new Object[] { account, account };
        List<Account> list = this.jdbcTemplate.query(sql, rowMapper, params);
        return list.size() == 1 ? list.get(0) : null;
    }

    public JsonObject userInfo(String account, String fromUser) {
        Account a = queryAsEntity(account);
        JsonObject info = new JsonObject();
        info.addProperty("username", a.getD_username());
        info.addProperty("sign", "Saltybe share fun with the world");
        info.addProperty("followerCount", 0);
        info.addProperty("followed", false);
        return info;
    }
}
